package com.niubi.yygh.orders.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.niubi.yygh.common.exception.YyghException;
import com.niubi.yygh.enums.OrderStatusEnum;
import com.niubi.yygh.enums.PaymentStatusEnum;
import com.niubi.yygh.model.order.OrderInfo;
import com.niubi.yygh.model.order.PaymentInfo;
import com.niubi.yygh.orders.mapper.PaymentInfoMapper;
import com.niubi.yygh.orders.service.OrderInfoService;
import com.niubi.yygh.orders.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 支付信息表 服务实现类
 * </p>
 *
 * @author 牛俊杰
 * @since 2022-03-30
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

  @Autowired
  private OrderInfoService orderInfoService;

  @Override
  public void savePaymentInfo(OrderInfo orderInfo) {
    QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
    wrapper.eq("order_id",orderInfo.getId());
    Integer count = baseMapper.selectCount(wrapper);
    if (count>0){
      return;
    }
    PaymentInfo paymentInfo = new PaymentInfo();
    paymentInfo.setCreateTime(new Date());
    paymentInfo.setOrderId(orderInfo.getId());
    paymentInfo.setPaymentType(1);
    paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
    paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
    String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")+"|"+orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle();
    paymentInfo.setSubject(subject);
    paymentInfo.setTotalAmount(orderInfo.getAmount());
    baseMapper.insert(paymentInfo);
  }

  @Override
  public void updateOrderStatus(String out_trade_no, Integer status, Map<String, String> resultMap) {
    QueryWrapper<OrderInfo> wrapperOrder = new QueryWrapper<>();
    wrapperOrder.eq("out_trade_no",out_trade_no);
    OrderInfo orderInfo = orderInfoService.getOne(wrapperOrder);
    if (orderInfo == null){
      throw new YyghException(20001,"支付信息不存在");
    }
    orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
    orderInfoService.updateById(orderInfo);

    QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
    wrapper.eq("out_trade_no",out_trade_no);
    PaymentInfo paymentInfo = baseMapper.selectOne(wrapper);
    if (paymentInfo == null){
      throw new YyghException(20001,"支付记录不存在");
    }
    paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
    paymentInfo.setTradeNo(resultMap.get("transaction_id"));
    paymentInfo.setCallbackTime(new Date());
    paymentInfo.setCallbackContent(resultMap.toString());
    baseMapper.updateById(paymentInfo);
  }
}
